package com.treetao.union.db.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.treetao.union.db.Const;
import com.treetao.union.db.mapper.MallPAttrMapper;
import com.treetao.union.db.model.MallPAttr;
import com.treetao.union.db.model.MallPAttrItem;
import com.treetao.union.db.model.MallPSkuAttrItem;
import com.treetao.union.db.service.MallPAttrItemService;
import com.treetao.union.db.service.MallPAttrService;
import com.treetao.union.db.service.MallPSkuAttrItemService;

/**
 * <p>
 * 商品属性 服务实现类
 * </p>
 *
 * @author Dev.M
 * @since 2020-04-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MallPAttrServiceImpl extends ServiceImpl<MallPAttrMapper, MallPAttr> implements MallPAttrService {

	@Autowired
	private MallPSkuAttrItemService mallPSkuAttrItemService;
	@Autowired
	private MallPAttrItemService mallPAttrItemService;
	
	@Override
	public List<MallPAttr> getAttrs(Long skuId) {
		List<MallPAttr> attrs = new ArrayList<MallPAttr>();
		//获取关系
		QueryWrapper<MallPSkuAttrItem> q = new QueryWrapper<MallPSkuAttrItem>();
		q.eq("ref_sku_id", skuId);
		List<MallPSkuAttrItem> refItems = mallPSkuAttrItemService.list(q);
		if(refItems==null || refItems.size()==0) {
			return attrs;
		}
		
		//获取所有属性值
		List<Long> listItemsIds = refItems.stream().map(item -> item.getRefAttrItemId()).collect(Collectors.toList());
		QueryWrapper<MallPAttrItem> q2 = new QueryWrapper<MallPAttrItem>();
		q2.in("id", listItemsIds);
		q2.eq("del_flag", false);
		List<MallPAttrItem> items = mallPAttrItemService.list(q2);
		if(items==null || items.size()==0) {
			return attrs;
		}
		
		//关联属性名称
		List<Long> listAttrIds = items.stream().map(item -> item.getRefAttrId()).distinct().collect(Collectors.toList());
		QueryWrapper<MallPAttr> q3 = new QueryWrapper<MallPAttr>();
		q3.in("id", listAttrIds);
		q3.eq("del_flag", false);
		attrs = list(q3);
		if(attrs==null || attrs.size()==0) {
			return attrs;
		}
		for(MallPAttr attr : attrs) {
			List<MallPAttrItem> listItems = items.stream().filter(item -> item.getRefAttrId().longValue()==attr.getId().longValue()).collect(Collectors.toList());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("attrItem", listItems);
			attr.setExts(map);
		}
		
		return attrs;
	}

}
